﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;

namespace NEvoWeb.Modules.NB_Store.Gateway
{
    public class GatewayPaymentOnDelivery : GatewayInterface
    {
        private const string GatewaySettingsName = "PaymentOnDelivery.gateway";
        private const string GatewayButtonName = "PaymentOnDelivery";
        private const string GatewayPayType = "PaymentOnDelivery";

        public override string GetButtonHtml(int PortalID, int OrderID, string Lang)
        {
            string returnValue = "";
            Hashtable hashtable = GatewayParams(PortalID);

            returnValue = string.Format("<input type='image' id='{0}' name='{0}' border='0' src='{1}' />", GatewayButtonName, Globals.ResolveUrl("~" + hashtable["ButtonImageURL"]));
            return returnValue;
        }

        public override bool GetBankClick(int PortalID, HttpRequest Request)
        {
            //add .x to the button name, since it is an image button, we receive both an imagebutton.x and imagebutton.y key....
            return ((Request.Form[GatewayButtonName + ".x"] != null));
        }

        public override void AutoResponse(int PortalID, HttpRequest Request)
        {
            // nothing to do here. No autoresponse in this gateway
        }

        public override string GetCompletedHtml(int PortalID, int UserID, HttpRequest Request)
        {
            SettingsController settingsController = new SettingsController();
            OrderController orderController = new OrderController();
            ProductController productController = new ProductController();
            int orderId = Null.NullInteger;
            string strSourceText = "";
            int.TryParse(Request.Form["ORDERID"], out orderId);

            strSourceText = settingsController.GetSettingsText(PortalID, "paymentSECURITY.text", SharedFunctions.GetCurrentCulture()).SettingText;
            if (orderId==Null.NullInteger)
            {
                return strSourceText;
            }

            var order = orderController.GetOrder(orderId);
            if (((order == null) || (order.UserID != UserID)))
            {
                return strSourceText;
            }

            if (((order != null)))
            {
                if (!order.OrderIsPlaced)
                {
                    //update stock level
                    productController.UpdateStockLevel(order.OrderID);

                    // update order
                    order.OrderStatusID = 46;
                    int userID = order.UserID;
                    if ((userID == -1))
                    {
                        userID = 0;
                    }
                    order.OrderNumber = string.Concat(new string[] {
								PortalID.ToString("00"),
								"-",
								userID.ToString("0000#"),
								"-",
								order.OrderID.ToString("0000#"),
								"-",
								order.OrderDate.ToString("yyyyMMdd")
							});
                    order.OrderIsPlaced = true;
                    orderController.UpdateObjOrder(order);

                    SharedFunctions.SendEmailToClient(PortalID, SharedFunctions.GetClientEmail(PortalID, order), order.OrderNumber, order, "paymentOK.email", SharedFunctions.GetCurrentCulture());
                    SharedFunctions.SendEmailToManager(PortalID, order.OrderNumber, order, "paymentOK.email");
                }

                //update order status
                ProductController pc = new ProductController();
                pc.UpdateModelQtyTrans(order.OrderID);
                order.PayType = GatewayPayType;
                order.OrderStatusID = 46;
                orderController.UpdateObjOrder(order);
                strSourceText = settingsController.GetSettingsText(PortalID, "paymentOK.text", SharedFunctions.GetCurrentCulture()).SettingText;
            }

            var replace = new TokenStoreReplace(order, SharedFunctions.GetMerchantCulture(PortalID));
            return replace.DoTokenReplace(strSourceText);
        }

        /// <summary>
        /// Creates the post to stage 5, since there is no bank-stage in this gateway
        /// </summary>
        /// <param name="PortalID"></param>
        /// <param name="OrderID"></param>
        /// <param name="Lang"></param>
        /// <param name="Request"></param>
        public override void SetBankRemotePost(int PortalID, int OrderID, string Lang, HttpRequest Request)
        {
            RemotePost post = new RemotePost();
            SettingsController controller = new SettingsController();
            NB_Store_SettingsInfo info = default(NB_Store_SettingsInfo);
            Hashtable hashtable = GatewayParams(PortalID);

            OrderController controller2 = new OrderController();
            NB_Store_OrdersInfo order = controller2.GetOrder(OrderID);
            if (((order != null)))
            {

                //since post.Inputs is private: we're building an identical local list here
                System.Collections.Specialized.NameValueCollection inputs = new System.Collections.Specialized.NameValueCollection();

                //add basic fields to form
                post.Add("ORDERID", order.OrderID.ToString());
                inputs.Add("ORDERID", order.OrderID.ToString());

                info = controller.GetSetting(PortalID, "gateway.loadimage", "None");
                post.Url = Globals.NavigateURL(int.Parse(SharedFunctions.GetStoreSetting(PortalID, "checkout.tab")),"","stg=5");

                // add form to cart, and update cart
                NB_Store_CartInfo currentCart = NEvoWeb.Modules.NB_Store.CurrentCart.GetCurrentCart(PortalID);
                currentCart.BankHtmlRedirect = post.GetPostHtml(info.SettingValue);
                NEvoWeb.Modules.NB_Store.CurrentCart.Save(currentCart);
            }
        }

        private Hashtable GatewayParams(int PortalId)
        {
            string @params = SharedFunctions.GetStoreSetting(PortalId, GatewaySettingsName, "None");

            //Get the gateway settings from the store setting Database
            if (!string.IsNullOrEmpty(@params))
            {
                //Parse the gateway setttings into a Hashtable for easy access.
                return createSettingsTable(@params);
            }
            else
            {
                throw new Exception("Setting not found: " + GatewaySettingsName);
            }

        }
        public Hashtable createSettingsTable(string SettingsParams)
        {
            return SharedFunctions.ParseGateway(SettingsParams);
        }

    }
}